#include <stdlib.h>
#include <string.h>
#include "student.h"

// 创建学生对象
Student* student_create(const char *name, int id, float score) {
    if (!name) {
        fprintf(stderr, "错误：姓名不能为空\n");
        return NULL;
    }

    Student *student = (Student*)malloc(sizeof(Student));
    if (!student) {
        fprintf(stderr, "错误：学生对象内存分配失败\n");
        return NULL;
    }

    // 为中文姓名分配内存
    student->name = (char*)malloc(strlen(name) + 1);
    if (!student->name) {
        fprintf(stderr, "错误：姓名内存分配失败\n");
        free(student);
        return NULL;
    }
    strcpy(student->name, name);

    student->id = id;
    student->score = score;

    return student;
}

// 销毁学生对象
void student_destroy(Student *student) {
    if (student) {
        free(student->name);  // 先释放姓名
        free(student);        // 再释放对象
    }
}

// 修改姓名
void student_set_name(Student *student, const char *new_name) {
    if (student && new_name) {
        char *new_name_buf = (char*)realloc(student->name, strlen(new_name) + 1);
        if (new_name_buf) {
            student->name = new_name_buf;
            strcpy(student->name, new_name);
        } else {
            fprintf(stderr, "错误：修改姓名内存分配失败\n");
        }
    }
}

// 修改分数
void student_set_score(Student *student, float new_score) {
    if (student) {
        student->score = new_score;
    }
}

// 获取姓名
const char* student_get_name(const Student *student) {
    return student ? student->name : NULL;
}

// 获取学号
int student_get_id(const Student *student) {
    return student ? student->id : -1;
}

// 获取分数
float student_get_score(const Student *student) {
    return student ? student->score : -1.0f;
}

// 打印学生信息
void student_print(const Student *student) {
    if (student) {
        printf("学号: %d, 姓名: %s, 分数: %.1f\n",
               student->id, student->name, student->score);
    }
}